<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Controller\AbstractController;
use Hyperf\HttpServer\Annotation\Middlewares;
use App\Middleware\AdminAuthMiddleware;
use App\Middleware\LoginAuthMiddleware;
use Hyperf\HttpServer\Annotation\Middleware;

/**
 * BaseController
 * 基类控制器
 * @package App\Controller\Admin
 */
class BaseController extends AbstractController
{
    
    /**
     * __get
     * 隐式注入仓库类
     * @param $key
     * @return \Psr\Container\ContainerInterface|void
     */
    public function __get($key)
    {
        if ($key == 'app') {
            return $this->container;
        } else {
            $suffix = strstr($key,'Repo');
            if ($suffix && ($suffix == 'Repo' || $suffix == 'Repository')) {
                $repoName = $suffix == 'Repo' ? $key.'sitory':$key;
                return $this->getRepositoriesInstance($repoName);
            } else {
                throw new \RuntimeException("仓库{$key}不存在，书写错误！", ErrorCode::ERR_SERVER);
            }
        }
    }

    /**
     * getRepositoriesInstance
     * 获取仓库类实例
     * @param $key
     * @return mixed
     */
    public function getRepositoriesInstance($key)
    {
        $key = ucfirst($key);
        $module = $this->getModuleName();
        if (!empty($module)) {
            $module = "{$module}";
        } else {
            $module = "";
        }
        if ($module) {
            $filename = BASE_PATH."/app/Core/Repository/{$module}/{$key}.php";
            $className = "Core\\Repository\\{$module}\\{$key}";
        } else {
            $filename = BASE_PATH."/app/Core/Repository/{$key}.php";
            $className = "Core\\Repository\\{$key}";
        }

        if (file_exists($filename)) {
            return $this->container->get($className);
        } else {
            throw new \RuntimeException("仓库{$key}不存在，文件不存在！", ErrorCode::ERR_SERVER);
        }
    }

    /**
     * getModuleName
     * 获取所属模块
     * @return string
     */
    private function getModuleName()
    {
        $className = get_called_class();
        $name = substr($className, 15);
        $space = explode('\\', $name);
        if(count($space) > 1){
            return $space[0];
        }else{
            return '';
        }
    }
}
